using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using SumerCoreDevOps.Infrastructure.Configuration;
using SumerCoreDevOps.Application.Dtos.Requests.SystemService;
namespace SumerCoreDevOps.ControlApi.Controllers;

/// <summary>
/// 系统服务控制 API
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class SystemServiceController : ControllerBase
{
    private readonly SystemConfigManager _configManager;
    private readonly ILogger<SystemServiceController> _logger;
    private readonly IHostApplicationLifetime _lifetime;

    public SystemServiceController(
        SystemConfigManager configManager,
        ILogger<SystemServiceController> logger,
        IHostApplicationLifetime lifetime)
    {
        _configManager = configManager;
        _logger = logger;
        _lifetime = lifetime;
    }

    /// <summary>
    /// 获取需要重启的配置列表
    /// </summary>
    /// <returns>返回包含需要重启才能生效的配置列表的对象,包括配置数量、配置详情(配置键、配置值、分类、描述、更新时间、更新人)、是否需要重启的布尔值以及各平台的重启说明;如果没有需要重启的配置则count为0且restartRequired为false;发生错误时返回500状态码和错误详情</returns>
    [HttpGet("pending-restart")]
    public async Task<ActionResult<object>> GetPendingRestartConfigs()
    {
        try
        {
            var configs = await _configManager.GetConfigsRequiringRestartAsync();

            return Ok(new
            {
                message = "获取需要重启的配置列表成功",
                count = configs.Count,
                configs = configs.Select(c => new
                {
                    c.ConfigKey,
                    c.ConfigValue,
                    c.Category,
                    c.Description,
                    c.UpdatedAt,
                    c.UpdatedBy
                }),
                restartRequired = configs.Count > 0,
                restartInstructions = new
                {
                    manual = "请手动重启 SumerCore DevOps 控制面板服务",
                    windows = "使用命令: sc stop SumerCoreDevOps && sc start SumerCoreDevOps",
                    linux = "使用命令: systemctl restart sumercore-devops",
                    docker = "使用命令: docker restart <container-name>"
                }
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取需要重启的配置列表失败");
            return StatusCode(500, new { message = "获取需要重启的配置列表失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 请求优雅关闭服务（需要由外部进程管理器重启）
    /// </summary>
    /// <returns>返回成功提示信息、关闭倒计时秒数以及各平台的重启说明;服务将在5秒后停止,需要由外部进程管理器(如systemd、Docker、Windows Service Manager)自动重启;发生错误时返回500状态码和错误详情</returns>
    [HttpPost("graceful-shutdown")]
    public ActionResult<object> RequestGracefulShutdown()
    {
        try
        {
            _logger.LogWarning("收到优雅关闭请求，将在5秒后关闭服务");

            // 延迟5秒后关闭，给请求足够的时间返回响应
            _ = Task.Run(async () =>
            {
                await Task.Delay(5000);
                _logger.LogInformation("开始优雅关闭服务");
                _lifetime.StopApplication();
            });

            return Ok(new
            {
                message = "已请求优雅关闭服务，服务将在5秒后停止",
                shutdownInSeconds = 5,
                instructions = new
                {
                    note = "服务停止后需要由外部进程管理器（如 systemd、Docker、Windows Service Manager）自动重启",
                    windows = "如果配置为 Windows 服务，服务管理器会自动重启",
                    linux = "如果配置为 systemd 服务，systemd 会根据配置自动重启",
                    docker = "如果运行在 Docker 中，确保容器配置了重启策略（如 --restart=always）"
                }
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "请求优雅关闭失败");
            return StatusCode(500, new { message = "请求优雅关闭失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 获取服务状态信息
    /// </summary>
    /// <returns>返回服务状态信息对象,包括运行状态、运行时长(uptime)、运行环境(environment)、平台信息、进程ID、机器名称、.NET版本等系统信息;发生错误时返回500状态码和错误详情</returns>
    [HttpGet("status")]
    public ActionResult<object> GetServiceStatus()
    {
        try
        {
            return Ok(new
            {
                status = "running",
                uptime = DateTime.UtcNow - System.Diagnostics.Process.GetCurrentProcess().StartTime.ToUniversalTime(),
                environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production",
                platform = Environment.OSVersion.Platform.ToString(),
                processId = Environment.ProcessId,
                machineName = Environment.MachineName,
                dotnetVersion = Environment.Version.ToString()
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取服务状态失败");
            return StatusCode(500, new { message = "获取服务状态失败", error = ex.Message });
        }
    }

    /// <summary>
    /// 检查配置变更后是否需要重启
    /// </summary>
    /// <returns>返回检查结果对象,包括requiresRestart布尔值(是否需要重启)、configsRequiringRestart列表(需要重启的配置键名列表)和提示信息;如果任一配置需要重启则requiresRestart为true;发生错误时返回500状态码和错误详情</returns>
    [HttpPost("check-restart-required")]
    public async Task<ActionResult<object>> CheckRestartRequired([FromBody] CheckRestartRequest request)
    {
        try
        {
            var requiresRestart = false;
            var configsRequiringRestart = new List<string>();

            foreach (var configKey in request.ConfigKeys)
            {
                var config = await _configManager.GetConfigAsync(configKey);
                if (config != null && config.RequiresRestart)
                {
                    requiresRestart = true;
                    configsRequiringRestart.Add(configKey);
                }
            }

            return Ok(new
            {
                requiresRestart,
                configsRequiringRestart,
                message = requiresRestart
                    ? $"配置 {string.Join(", ", configsRequiringRestart)} 需要重启服务才能生效"
                    : "配置变更不需要重启服务"
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "检查重启要求失败");
            return StatusCode(500, new { message = "检查重启要求失败", error = ex.Message });
        }
    }
}
